package top.appx.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.appx.util.ResultUtil;
import top.appx.vo.Result;

import javax.servlet.http.HttpServletResponse;

/**
 * Created by lhzxd on 2017/5/3.
 */
@RestControllerAdvice
public class SuperExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(SuperExceptionHandler.class);


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception ex){
        logger.error("系统错误",ex);
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = attributes.getResponse();
        response.setStatus(500);

        if(ex instanceof BindException){
            return ResultUtil.error("系统错误(输入验证失败:"+((BindException) ex).getFieldError().getDefaultMessage()+")");
        }

        return ResultUtil.error("系统错误:"+ex.getClass().getName());
    }
}
